<route lang="json5">
{
  style: {
    navigationBarTitleText: '个人资料',
  },
}
</route>

<template>
  <view class="h-screen bg-gray-100 overflow-hidden">
    <keyboard-avoiding-view>
      <scroll-view scroll-y class="h-full" enable-flex>
        <view class="p-4 pb-safe">
          <view class="bg-white rounded-3xl shadow-md overflow-hidden">
            <view class="p-4">
              <!-- #ifdef MP-WEIXIN -->
              <view class="flex justify-center mb-6">
                <button
                  open-type="chooseAvatar"
                  @chooseavatar="onChooseAvatar"
                  class="avatar-button"
                >
                  <image
                    :src="formData.avatar || '/static/default-avatar.png'"
                    class="avatar-image"
                    mode="aspectFill"
                  />
                </button>
              </view>
              <!-- #endif -->

              <view class="space-y-5">
                <!-- 姓名 -->
                <view class="flex items-center py-3 rounded-xl">
                  <text class="w-24 text-[#333]" :style="{ fontSize: settings.fontSize }">
                    姓名
                  </text>
                  <input
                    v-model="formData.name"
                    :style="{ fontSize: settings.fontSize }"
                    class="flex-1 text-right text-[#333] bg-transparent outline-none"
                    placeholder="请输入姓名"
                    placeholder-style="color: #aaa;"
                  />
                </view>

                <!-- 公司名称 -->
                <view class="flex items-center py-3 rounded-xl">
                  <text class="w-24 text-[#333]" :style="{ fontSize: settings.fontSize }">
                    公司名称
                  </text>
                  <input
                    v-model="formData.companyName"
                    :style="{ fontSize: settings.fontSize }"
                    class="flex-1 text-right text-[#333] bg-transparent outline-none"
                    placeholder="请输入公司名称"
                    placeholder-style="color: #aaa;"
                  />
                </view>

                <!-- 职位 -->
                <view class="flex items-center py-3 rounded-xl">
                  <text class="w-24 text-[#333]" :style="{ fontSize: settings.fontSize }">
                    职位
                  </text>
                  <input
                    v-model="formData.position"
                    :style="{ fontSize: settings.fontSize }"
                    class="flex-1 text-right text-[#333] bg-transparent outline-none"
                    placeholder="请输入职位"
                    placeholder-style="color: #aaa;"
                  />
                </view>

                <!-- 性别（弹出菜单选择） -->
                <view class="flex items-center py-3 rounded-xl" @click="chooseGender">
                  <text class="w-24 text-[#333]" :style="{ fontSize: settings.fontSize }">
                    性别
                  </text>
                  <text
                    class="flex-1 text-right text-[#333]"
                    :style="{
                      fontSize: settings.fontSize,
                      color: formData.gender ? '#333' : '#aaa',
                    }"
                  >
                    {{ formData.gender || '请选择性别' }}
                  </text>
                  <wd-icon name="arrow-right" size="16px" color="#ccc" />
                </view>
              </view>
            </view>
          </view>
        </view>
        <!-- 保存按钮 -->
        <view class="flex justify-center mt-8">
          <view
            class="w-80 h-12 rounded-full text-center leading-[48px] font-medium shadow-md active:scale-95 transition-transform duration-200"
            :style="{
              background: `linear-gradient(to right, ${settings.themeColor}, ${settings.themeColor})`,
              color: '#fff',
              fontSize: settings.fontSize,
            }"
            @click="handleSubmit"
          >
            保存修改
          </view>
        </view>
      </scroll-view>
    </keyboard-avoiding-view>
  </view>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useToast } from 'wot-design-uni'
import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
import { updateInfo } from '@/api/login'
import { useSettingsStore } from '@/store/settings'

const toast = useToast()
const settings = useSettingsStore()
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)

const formData = ref({
  userId: -1,
  name: '',
  avatar: '',
  companyName: '',
  position: '',
  gender: '',
})

onShow(() => {
  resetInfo()
})

const resetInfo = () => {
  formData.value = {
    userId: userInfo.value.userId,
    name: userInfo.value.name || '',
    avatar: userInfo.value.avatar || '',
    companyName: userInfo.value.companyName || '',
    position: userInfo.value.position || '',
    gender: userInfo.value.gender || '',
  }
}

// 微信头像选择
const onChooseAvatar = (e: any) => {
  const avatarUrl = e.detail.avatarUrl
  uni.getFileSystemManager().readFile({
    filePath: avatarUrl,
    encoding: 'base64',
    success: (res) => {
      const ext = avatarUrl.split('.').pop()?.toLowerCase() || 'jpeg'
      const mimeMap = {
        png: 'image/png',
        jpg: 'image/jpeg',
        jpeg: 'image/jpeg',
        gif: 'image/gif',
      }
      const base64DataUrl = `data:${mimeMap[ext] || 'image/jpeg'};base64,${res.data}`
      formData.value.avatar = base64DataUrl
    },
    fail: (err) => {
      console.error('读取头像失败:', err)
      toast.error('读取头像失败')
    },
  })
}

// 性别选择弹出
const chooseGender = () => {
  uni.showActionSheet({
    itemList: ['男', '女'],
    success: (res) => {
      formData.value.gender = res.tapIndex === 0 ? '男' : '女'
    },
    fail: () => {},
  })
}

const handleSubmit = async () => {
  if (!formData.value.name.trim()) return toast.error('请输入姓名')
  if (!formData.value.companyName.trim()) return toast.error('请输入公司名称')
  if (!formData.value.gender) return toast.error('请选择性别')

  try {
    const { data } = await updateInfo(formData.value)
    console.log('修改结果', data)
    toast.success('修改成功')
    userStore.getUserInfo(formData.value.userId)
    setTimeout(() => {
      uni.navigateBack()
    }, 1000)
  } catch (err) {
    toast.error('保存失败，请重试')
  }
}
</script>

<style scoped>
.pb-safe {
  padding-bottom: env(safe-area-inset-bottom);
}
input {
  height: 100%;
  line-height: inherit;
}

.avatar-button {
  width: 96rpx;
  height: 96rpx;
  padding: 0;
  border-radius: 50%;
  overflow: hidden;
  border: 4rpx solid #eee;
  background-color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-image {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
}
</style>
